from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import json
import os

import sys
import os
# 添加项目根目录到Python路径
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)
from ocr_service import recognize_image, recognize_images_batch, check_ocr_service

# Create your views here.

@csrf_exempt
@require_http_methods(["POST"])
def ocr_recognize(request):
    """
    单张图片OCR识别接口
    """
    try:
        # 检查是否有文件上传
        if 'image' not in request.FILES:
            return JsonResponse({
                'success': False,
                'error': '没有上传图片文件'
            }, status=400)
        
        image_file = request.FILES['image']
        
        # 检查文件大小（限制10MB）
        if image_file.size > 10 * 1024 * 1024:
            return JsonResponse({
                'success': False,
                'error': '文件大小超过10MB限制'
            }, status=400)
        
        # 调用OCR服务
        result = recognize_image(image_file, image_file.name)
        
        if result.get('success'):
            return JsonResponse(result)
        else:
            return JsonResponse(result, status=500)
            
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'处理失败: {str(e)}'
        }, status=500)

@csrf_exempt
@require_http_methods(["POST"])
def ocr_batch(request):
    """
    批量图片OCR识别接口
    """
    try:
        # 检查是否有文件上传
        if 'images' not in request.FILES:
            return JsonResponse({
                'success': False,
                'error': '没有上传图片文件'
            }, status=400)
        
        image_files = request.FILES.getlist('images')
        
        if not image_files:
            return JsonResponse({
                'success': False,
                'error': '没有选择文件'
            }, status=400)
        
        # 检查文件数量（限制20个）
        if len(image_files) > 20:
            return JsonResponse({
                'success': False,
                'error': '文件数量超过20个限制'
            }, status=400)
        
        # 检查文件大小
        for image_file in image_files:
            if image_file.size > 10 * 1024 * 1024:
                return JsonResponse({
                    'success': False,
                    'error': f'文件 {image_file.name} 大小超过10MB限制'
                }, status=400)
        
        # 调用OCR服务
        result = recognize_images_batch(image_files)
        
        if result.get('success'):
            return JsonResponse(result)
        else:
            return JsonResponse(result, status=500)
            
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'处理失败: {str(e)}'
        }, status=500)

@require_http_methods(["GET"])
def ocr_status(request):
    """
    OCR服务状态检查接口
    """
    try:
        is_available, status_info = check_ocr_service()
        
        return JsonResponse({
            'success': True,
            'data': {
                'available': is_available,
                'status': status_info,
                'timestamp': status_info.get('timestamp', '')
            }
        })
        
    except Exception as e:
        return JsonResponse({
            'success': False,
            'error': f'检查失败: {str(e)}'
        }, status=500)

@require_http_methods(["GET"])
def ocr_test(request):
    """
    OCR服务测试页面
    """
    return render(request, 'ocr_test.html')
